import cv2
import time
from HandTrackingModule import HandDetector
import pyautogui
import numpy as np
###################################
wCam, hCam = 1920, 1080  # 定义画面尺寸
framR = 50  # 限定的尺寸
smoothening = 7  # 平滑度
###################################
wScr, hScr = pyautogui.size()  # 自动获取屏幕尺寸
pre = 0  # 先前的坐标值
cur = 0  # 当前的坐标值
pt1, pt2 = (100,100), (300, 300)   # 虚拟鼠标的移动范围，左上坐标pt1，右下坐标pt2

def main():
    pTime = 0
    cap = cv2.VideoCapture(0)
    detector = HandDetector(detectionCon=0.8, maxHands=2)

    while cap:
        success, img = cap.read()
        hands, img = detector.findHands(img)  # with draw
        img = cv2.flip(img, 1)  # 水平翻转，因为摄像头拍的是镜像的。

        for hand in hands:
            if len(hands)==1 and hand["type"] == "Right":  # 单手手势
                print(detector.fingersUp(hands[0]))
                fingers_1 = detector.fingersUp(hands[0])
                if fingers_1 == [0, 1, 0, 0, 0]:  # 上
                    pyautogui.press('left')
                    time.sleep(0.2)
                elif fingers_1 == [0, 0, 1, 1, 1]:  # 下 不灵敏
                    pyautogui.press('right')
                    time.sleep(0.5)
                elif fingers_1 == [1, 1, 0, 0, 0]:  # 播放当前
                    pyautogui.hotkey('shift', 'F5')
                    pyautogui.keyDown('ctrl')
                    pyautogui.scroll(100)
                    pyautogui.keyUp('ctrl')
                    time.sleep(0.2)
                elif fingers_1 == [1, 1, 1, 1, 1]:  # 退出当前
                    pyautogui.press('esc')
                    time.sleep(0.2)
                elif fingers_1 == [0, 1, 1, 1, 1]:  # 放大
                    pyautogui.hotkey('ctrl', '+')
                    time.sleep(0.2)
                elif fingers_1 == [0, 1, 1, 0, 0]:  # 缩小
                    pyautogui.hotkey('ctrl', '-')
                    time.sleep(0.2)
                elif fingers_1 == [1, 0, 0, 0, 0]:  # 左旋
                    pyautogui.hotkey('ctrl', 'l')
                    print("l")
                    time.sleep(0.8)
                elif fingers_1 == [0, 0, 0, 0, 1]:  # 右旋
                    pyautogui.hotkey('ctrl', 'r')
                    print("r")
                    time.sleep(0.8)

        # --------------FPS显示--------------
        cTime = time.time()
        fps = 1 / (cTime - pTime)
        pTime = cTime
        cv2.putText(img, f'FPS={int(fps)}', (20, 50), cv2.FONT_HERSHEY_COMPLEX, 2, (255, 255, 255), 2)

        cv2.imshow('windowName', img)

        # 点击小写字母q 退出程序
        if cv2.waitKey(1) == ord('q'):
            break

        # 点击窗口关闭按钮退出程序
        if cv2.getWindowProperty('windowName', cv2.WND_PROP_AUTOSIZE) < 1:
            break

    cap.release()
    cv2.destroyAllWindows()


if __name__ == "__main__":
    main()
